﻿using Kingdee.BOS;
using Kingdee.BOS.App.Core.ScheduleService;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Contracts;
using Kingdee.BOS.Core;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.NotePrint;
using Kingdee.BOS.JSON;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Orm.Metadata.DataEntity;
using Kingdee.BOS.Resource;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace LianKe.LianKeSchedule
{
    public class BackgroundPrintTaskService : IScheduleService
    {
        //public void AddPrintData(Context ctx, string taskId, string printerName, string printData)
        //{
        //    throw new NotImplementedException();
        //}

        //public void AddPrintData(Context ctx, string taskId, string entryId, string printerName, string printData)
        //{
        //    throw new NotImplementedException();
        //}

        //public void AddPrintDataDetailPageByPage(Context ctx, string entryId, List<Tuple<int, string>> printDataList)
        //{
        //    throw new NotImplementedException();
        //}

        //public void AddPrintTask(Context ctx, string taskId, string taskName, string formId, string schemeId, string filterParamter, string queryParamter, string context, string printParamter, string pageParamter, int actionTypeId, int operationTypeId, string exportmode)
        //{
        //    throw new NotImplementedException();
        //}

        public IDynamicFormView CreateView(Context ctx, DynamicObject task, bool replaceCtx)
        {
            Type orRegister = TypesContainer.GetOrRegister("Kingdee.BOS.Web.Utils.WebServiceViewBuilder,Kingdee.BOS.Web");
            object obj = Activator.CreateInstance(orRegister);
            MethodInfo method = obj.GetType().GetMethod("CreateView");
            object obj2 = method.Invoke(obj, new object[3] { ctx, task, replaceCtx });
            return (IDynamicFormView)((obj2 is IDynamicFormView) ? obj2 : null);
        }

        //public string GetBackGroundPrintTaskCreator(Context ctx, string taskId)
        //{
        //    throw new NotImplementedException();
        //}

        //public DynamicObject GetPrintData(Context ctx, string subTaskId)
        //{
        //    throw new NotImplementedException();
        //}

        //public DynamicObjectCollection GetPrintDataDetailPageByPage(Context ctx, string subTaskId, int pageIdx, int pageCount)
        //{
        //    throw new NotImplementedException();
        //}

        //public DynamicObjectCollection GetPrintDataList(Context ctx, string taskId, bool readPrintData = false)
        //{
        //    throw new NotImplementedException();
        //}

        //public DynamicObjectCollection GetPrintTaskList(Context ctx, string[] ids)
        //{
        //    throw new NotImplementedException();
        //}

        public void Run(Context ctx, Schedule schedule)
        {
            long userId = ctx.UserId;
            OrganizationInfo currentOrganizationInfo = ctx.CurrentOrganizationInfo;
            try
            {
                DoBackgroundPrintTask(ctx, schedule);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                ctx.UserId = userId;
                ctx.CurrentOrganizationInfo = currentOrganizationInfo;
            }
        }

        private void DoBackgroundPrintTask(Context ctx, Schedule schedule)
        {
            string text = $"select * from t_bos_printtask where fstatus='{0}'";
            DynamicObjectCollection val = DBUtils.ExecuteDynamicObject(ctx, text, (IDataEntityType)null, (IDictionary<string, Type>)null, CommandType.Text, (SqlParam[])(object)new SqlParam[0]);
            if (val == null || ((Collection<DynamicObject>)(object)val).Count <= 0)
            {
                //schedule.Status = (ScheduleStatus)1;
                //schedule.Notes = string.Format("后台打印任务中没有需要计算的数据，自动停止执行计划，时间：{0}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff"));
                //ScheduleWriter scheduleWriter = new ScheduleWriter();
                //scheduleWriter.UpdateExecuteTime(ctx, schedule);
                return;
            }
            foreach (DynamicObject item in (Collection<DynamicObject>)(object)val)
            {
                if (SetPrintTaskDoing(ctx, item["FID"].ToString()) <= 0)
                {
                    continue;
                }
                IDynamicFormView view;
                try
                {
                    view = CreateView(ctx, item, replaceCtx: true);
                }
                catch (Exception ex)
                {
                    string text2 = ex.Message;
                    if (ex.InnerException != null)
                    {
                        text2 = text2 + ";InnerException:" + ex.InnerException.Message;
                    }
                    SetPrintTaskFailure(ctx, item["FID"].ToString(), ResManager.LoadKDString("重建视图异常:", "002002030032360", (SubSystemType)2, new object[0]) + text2);
                    continue;
                }
                if (item["FACTIONTYPEID"].ToString() == 0.ToString())
                {
                    try
                    {
                        List<PrintJob> printParamter = GetPrintParamter(item["fprintparamter"].ToString());
                        CreatePrintData(view, printParamter);
                        UpdatePrintTaskStatus(ctx, item["FID"].ToString(), 2);
                    }
                    catch (Exception ex2)
                    {
                        string text2 = ex2.Message;
                        if (ex2.InnerException != null)
                        {
                            text2 = text2 + ";InnerException:" + ex2.InnerException.Message;
                        }
                        SetPrintTaskFailure(ctx, item["FID"].ToString(), ResManager.LoadKDString("打印取数异常:", "002002030032361", (SubSystemType)2, new object[0]) + text2);
                    }
                }
                else if (item["FACTIONTYPEID"].ToString() == 5.ToString())
                {
                    try
                    {
                        PrintExportInfo exportParamter = GetExportParamter(item["fprintparamter"].ToString());
                        CreateNoteExportData(view, exportParamter);
                        UpdatePrintTaskStatus(ctx, item["FID"].ToString(), 2);
                    }
                    catch (Exception ex3)
                    {
                        string text2 = ex3.Message;
                        if (ex3.InnerException != null)
                        {
                            text2 = text2 + ";InnerException:" + ex3.InnerException.Message;
                        }
                        SetPrintTaskFailure(ctx, item["FID"].ToString(), ResManager.LoadKDString("套打引出取数异常:", "002002030032362", (SubSystemType)2, new object[0]) + text2);
                    }
                }
                else if (item["FACTIONTYPEID"].ToString() == 10.ToString())
                {
                    try
                    {
                        CreateListExportData(view, item["FID"].ToString());
                        UpdatePrintTaskStatus(ctx, item["FID"].ToString(), 2);
                    }
                    catch (Exception ex4)
                    {
                        string text2 = ex4.Message;
                        if (ex4.InnerException != null)
                        {
                            text2 = text2 + ";InnerException:" + ex4.InnerException.Message;
                        }
                        SetPrintTaskFailure(ctx, item["FID"].ToString(), ResManager.LoadKDString("列表引出取数异常:", "002002030032441", (SubSystemType)2, new object[0]) + text2);
                    }
                }
                else
                {
                    SetPrintTaskFailure(ctx, item["FID"].ToString(), ResManager.LoadKDString("任务类型未定义", "002002030032363", (SubSystemType)2, new object[0]));
                }
            }
        }

        private void CreateListExportData(IDynamicFormView view, string taskId)
        {
            Type orRegister = TypesContainer.GetOrRegister("Kingdee.BOS.Web.Printing.ExportService,Kingdee.BOS.Web");
            object obj = Activator.CreateInstance(orRegister);
            MethodInfo method = obj.GetType().GetMethod("CreateBackgroundListExportData");
            method.Invoke(obj, new object[2] { view, taskId });
        }

        private void CreateNoteExportData(IDynamicFormView view, PrintExportInfo parameter)
        {
            Type orRegister = TypesContainer.GetOrRegister("Kingdee.BOS.Web.Printing.NotePrintService,Kingdee.BOS.Web");
            object obj = Activator.CreateInstance(orRegister);
            MethodInfo method = obj.GetType().GetMethod("AddBackgroundExport");
            method.Invoke(obj, new object[2] { view, parameter });
        }

        private PrintExportInfo GetExportParamter(string printParamter)
        {
            try
            {
                return KDObjectConverter.DeserializeObject<PrintExportInfo>(printParamter);
            }
            catch
            {
                throw new KDException("###", ResManager.LoadKDString("引出参数无效", "002002030032357", (SubSystemType)2, new object[0]));
            }
        }

        private void CreatePrintData(IDynamicFormView view, List<PrintJob> parameter)
        {
            Type orRegister = TypesContainer.GetOrRegister("Kingdee.BOS.Web.Printing.NotePrintService,Kingdee.BOS.Web");
            object obj = Activator.CreateInstance(orRegister);
            MethodInfo method = obj.GetType().GetMethod("AddBackgroundReport");
            method.Invoke(obj, new object[3] { view, parameter, "print" });
        }

        private List<PrintJob> GetPrintParamter(string printParamter)
        {
            try
            {
                return KDObjectConverter.DeserializeObject<List<PrintJob>>(printParamter);
            }
            catch
            {
                throw new KDException("###", ResManager.LoadKDString("打印参数无效", "002002030032256", (SubSystemType)2, new object[0]));
            }
        }

        public void SetPrintTaskFailure(Context ctx, string taskId, string errorMsg)
        {
            string text = "update t_bos_printtask set fstatus=@fstatus,ferrormsg=@ferrormsg where fid=@fid";
            List<SqlParam> list = new List<SqlParam>();
            list.Add(new SqlParam("@fid", (KDDbType)16, (object)taskId));
            list.Add(new SqlParam("@fstatus", (KDDbType)0, (object)3));
            list.Add(new SqlParam("@ferrormsg", (KDDbType)16, (object)errorMsg));
            DBUtils.Execute(ctx, text, (IEnumerable<SqlParam>)list.ToArray());
        }

        private int SetPrintTaskDoing(Context ctx, string taskId)
        {
            string text = "update t_bos_printtask set fstatus=@fstatus where fid=@fid and fstatus=@fstatus1";
            List<SqlParam> list = new List<SqlParam>();
            list.Add(new SqlParam("@fid", (KDDbType)0, (object)taskId));
            list.Add(new SqlParam("@fstatus", (KDDbType)0, (object)1));
            list.Add(new SqlParam("@fstatus1", (KDDbType)0, (object)0));
            return DBUtils.Execute(ctx, text, (IEnumerable<SqlParam>)list.ToArray());
        }

        public void UpdatePrintTaskStatus(Context ctx, string taskId, int status)
        {
            string text = "update t_bos_printtask set fstatus=@fstatus where fid=@fid";
            List<SqlParam> list = new List<SqlParam>();
            list.Add(new SqlParam("@fid", (KDDbType)0, (object)taskId));
            list.Add(new SqlParam("@fstatus", (KDDbType)0, (object)status));
            DBUtils.Execute(ctx, text, (IEnumerable<SqlParam>)list.ToArray());
        }
    }
}
